<?php
// 更新菜品信息并标记ai_called字段

require_once '../thinkphp/base.php';

use think\Db;

function updateDishInfo($dishId, $dishInfo) {
    // 开始事务
    Db::startTrans();
    try {
        // 更新菜品信息
        $updateData = [
            'steps' => $dishInfo['steps'] ?? '',
            'cook_time' => $dishInfo['cook_time'] ?? '',
            'updatetime' => time()
        ];
        
        Db::name('food_dish')->where('id', $dishId)->update($updateData);
        
        // 删除原有的食材关联
        Db::name('food_ingredientrel')->where('dish_id', $dishId)->delete();
        
        // 添加新的食材关联
        if (!empty($dishInfo['ingredients'])) {
            $insertData = [];
            foreach ($dishInfo['ingredients'] as $index => $ingredient) {
                if (isset($ingredient['id']) && $ingredient['id'] > 0) {
                    $insertData[] = [
                        'dish_id' => $dishId,
                        'ingredient_id' => intval($ingredient['id']),
                        'quantity' => $ingredient['quantity'] ?? '100g',
                        'createtime' => time(),
                        'weigh' => $index + 1
                    ];
                }
            }
            
            if (!empty($insertData)) {
                Db::name('food_ingredientrel')->insertAll($insertData);
            }
        }
        
        // 标记为已调用AI
        Db::name('food_dish')->where('id', $dishId)->update(['ai_called' => 1]);
        
        // 提交事务
        Db::commit();
        return true;
    } catch (\Exception $e) {
        // 回滚事务
        Db::rollback();
        echo "更新菜品ID {$dishId} 失败: " . $e->getMessage() . "\n";
        return false;
    }
}

// 示例用法
// $dishInfo = [
//     'steps' => '1. 热锅凉油...',
//     'cook_time' => '10分钟',
//     'ingredients' => [
//         ['id' => 1, 'name' => '鸡蛋', 'quantity' => '150克'],
//         ['id' => 2, 'name' => '西红柿', 'quantity' => '300克']
//     ]
// ];
// updateDishInfo(1, $dishInfo);
?>